<template>
  <div class="login-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户登录</span>
      </div>
      <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="120px">
        <el-form-item label="登录ID" prop="loginId">
          <el-input v-model="loginForm.loginId"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '../../utils/request';

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        loginId: '',
        password: ''
      },
      rules: {
        loginId: [{ required: true, message: '请输入登录ID', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          request.post('/user/login', this.loginForm)
              .then(response => {
                if (response.code === '200') {
                  this.$message.success('登录成功');
                  // 保存用户信息到本地存储
                  localStorage.setItem('loginId', response.data.loginId);
                  localStorage.setItem('username', response.data.username);
                  localStorage.setItem('isAdmin', response.data.loginId === 'admin');
                  // 跳转到首页或其他页面
                  this.$router.push({ path: '/' });
                } else {
                  this.$message.error(response.message || '登录失败');
                }
              })
              .catch(error => {
                console.error('Error logging in:', error);
                this.$message.error('登录失败');
              });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.box-card {
  width: 400px;
}
</style>